// 主应用程序入口
class SandboxApp {
    constructor() {
        this.sandboxCanvas = null;
        this.websocketManager = null;
        this.initialized = false;

        // 等待DOM加载完成
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', () => this.init());
        } else {
            this.init();
        }
    }

    init() {
        console.log('初始化沙盘应用...');

        try {
            // 初始化沙盘画布
            this.sandboxCanvas = new SandboxCanvas('sandbox-canvas');
            window.sandboxCanvas = this.sandboxCanvas; // 全局引用

            // 初始化WebSocket管理器
            this.websocketManager = new WebSocketManager();
            window.websocketManager = this.websocketManager; // 全局引用

            // 绑定UI事件
            this.bindUIEvents();

            // 设置iPad优化
            this.setupMobileOptimizations();

            this.initialized = true;
            console.log('沙盘应用初始化完成');

        } catch (error) {
            console.error('初始化失败:', error);
            this.showError('应用初始化失败: ' + error.message);
        }
    }

    bindUIEvents() {
        // 清空按钮
        const clearBtn = document.getElementById('clear-btn');
        if (clearBtn) {
            clearBtn.addEventListener('click', () => {
                if (confirm('确定要清空沙盘吗？')) {
                    this.sandboxCanvas.clear();
                }
            });
        }

        // 重置按钮
        const resetBtn = document.getElementById('reset-btn');
        if (resetBtn) {
            resetBtn.addEventListener('click', () => {
                if (confirm('确定要重置所有设置吗？')) {
                    this.sandboxCanvas.reset();
                }
            });
        }

        // 全屏按钮
        const fullscreenBtn = document.getElementById('fullscreen-btn');
        if (fullscreenBtn) {
            fullscreenBtn.addEventListener('click', () => {
                this.toggleFullscreen();
            });
        }

        // 添加建筑按钮
        const addBuildingBtn = document.getElementById('add-building-btn');
        if (addBuildingBtn) {
            addBuildingBtn.addEventListener('click', () => {
                this.enableObjectPlacement('building');
            });
        }

        // 添加树木按钮
        const addTreeBtn = document.getElementById('add-tree-btn');
        if (addTreeBtn) {
            addTreeBtn.addEventListener('click', () => {
                this.enableObjectPlacement('tree');
            });
        }

        // 画笔大小滑块
        const brushSizeSlider = document.getElementById('brush-size');
        const brushSizeValue = document.getElementById('brush-size-value');
        if (brushSizeSlider && brushSizeValue) {
            brushSizeSlider.addEventListener('input', (e) => {
                const size = parseInt(e.target.value);
                brushSizeValue.textContent = size;
                this.sandboxCanvas.setBrushSize(size);
            });
        }

        // 透明度滑块
        const opacitySlider = document.getElementById('opacity');
        const opacityValue = document.getElementById('opacity-value');
        if (opacitySlider && opacityValue) {
            opacitySlider.addEventListener('input', (e) => {
                const opacity = parseInt(e.target.value);
                opacityValue.textContent = opacity + '%';
                this.sandboxCanvas.setOpacity(opacity);
            });
        }

        // 键盘快捷键
        document.addEventListener('keydown', (e) => {
            this.handleKeyboardShortcuts(e);
        });

        // 阻止页面滚动（iPad优化）
        document.addEventListener('touchmove', (e) => {
            if (e.target.closest('#sandbox-canvas')) {
                e.preventDefault();
            }
        }, { passive: false });
    }

    handleKeyboardShortcuts(e) {
        // Ctrl/Cmd + Z: 撤销（暂未实现）
        if ((e.ctrlKey || e.metaKey) && e.key === 'z') {
            e.preventDefault();
            console.log('撤销功能暂未实现');
        }

        // Ctrl/Cmd + Shift + Z: 重做（暂未实现）
        if ((e.ctrlKey || e.metaKey) && e.shiftKey && e.key === 'z') {
            e.preventDefault();
            console.log('重做功能暂未实现');
        }

        // Delete: 清空画布
        if (e.key === 'Delete') {
            e.preventDefault();
            if (confirm('确定要清空沙盘吗？')) {
                this.sandboxCanvas.clear();
            }
        }

        // Escape: 断开连接
        if (e.key === 'Escape') {
            e.preventDefault();
            if (this.websocketManager.isConnected()) {
                this.websocketManager.disconnect();
            }
        }

        // Space: 连接/断开切换
        if (e.key === ' ' && e.target.tagName !== 'INPUT') {
            e.preventDefault();
            if (this.websocketManager.isConnected()) {
                this.websocketManager.disconnect();
            } else {
                this.websocketManager.connect();
            }
        }
    }

    setupMobileOptimizations() {
        // 检测设备类型
        const isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
        const isIPad = /iPad/.test(navigator.userAgent) || (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1);

        if (isMobile || isIPad) {
            console.log('检测到移动设备，启用移动优化');

            // 添加移动设备样式类
            document.body.classList.add('mobile-device');

            if (isIPad) {
                document.body.classList.add('ipad-device');
                this.setupIPadOptimizations();
            }

            // 禁用双击缩放
            let lastTouchEnd = 0;
            document.addEventListener('touchend', (e) => {
                const now = (new Date()).getTime();
                if (now - lastTouchEnd <= 300) {
                    e.preventDefault();
                }
                lastTouchEnd = now;
            }, false);

            // 优化触摸响应
            document.addEventListener('touchstart', () => { }, { passive: true });

            // 显示手势提示
            this.showGestureHint();
        }

        // 处理屏幕方向变化
        window.addEventListener('orientationchange', () => {
            setTimeout(() => {
                this.sandboxCanvas.resizeCanvas();
                this.handleOrientationChange();
            }, 100);
        });

        // 处理窗口大小变化
        let resizeTimeout;
        window.addEventListener('resize', () => {
            clearTimeout(resizeTimeout);
            resizeTimeout = setTimeout(() => {
                this.sandboxCanvas.resizeCanvas();
            }, 250);
        });
    }

    // 添加沙盘对象的便捷方法
    addBuilding(x, y, color = '#3498db') {
        return this.sandboxCanvas.addObject('building', x, y, { color });
    }

    addTree(x, y) {
        return this.sandboxCanvas.addObject('tree', x, y);
    }

    addRoad(x, y, endX, endY) {
        return this.sandboxCanvas.addObject('road', x, y, { endX, endY });
    }

    // 错误处理
    showError(message) {
        console.error(message);

        // 创建错误提示
        const errorDiv = document.createElement('div');
        errorDiv.style.cssText = `
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: #e74c3c;
            color: white;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.3);
            z-index: 10000;
            max-width: 400px;
            text-align: center;
        `;
        errorDiv.innerHTML = `
            <h3>错误</h3>
            <p>${message}</p>
            <button onclick="this.parentNode.remove()" style="
                background: white;
                color: #e74c3c;
                border: none;
                padding: 8px 16px;
                border-radius: 5px;
                margin-top: 10px;
                cursor: pointer;
            ">确定</button>
        `;

        document.body.appendChild(errorDiv);

        // 5秒后自动移除
        setTimeout(() => {
            if (errorDiv.parentNode) {
                errorDiv.parentNode.removeChild(errorDiv);
            }
        }, 5000);
    }

    // 获取应用状态
    getStatus() {
        return {
            initialized: this.initialized,
            connected: this.websocketManager ? this.websocketManager.isConnected() : false,
            canvasSize: {
                width: this.sandboxCanvas ? this.sandboxCanvas.canvas.width : 0,
                height: this.sandboxCanvas ? this.sandboxCanvas.canvas.height : 0
            },
            objectCount: this.sandboxCanvas ? this.sandboxCanvas.objects.length : 0
        };
    }

    // 导出沙盘数据
    exportData() {
        if (!this.sandboxCanvas) return null;

        return {
            objects: this.sandboxCanvas.objects,
            canvasData: this.sandboxCanvas.canvas.toDataURL(),
            timestamp: Date.now(),
            version: '1.0'
        };
    }

    // 导入沙盘数据
    importData(data) {
        if (!this.sandboxCanvas || !data) return false;

        try {
            // 清空当前画布
            this.sandboxCanvas.clear();

            // 导入对象
            if (data.objects) {
                data.objects.forEach(obj => {
                    this.sandboxCanvas.objects.push(obj);
                    this.sandboxCanvas.drawObject(obj);
                });
            }

            return true;
        } catch (error) {
            console.error('导入数据失败:', error);
            return false;
        }
    }

    // iPad专用优化
    setupIPadOptimizations() {
        // 高DPI画布优化
        this.optimizeCanvasForHighDPI();

        // 多点触控支持
        this.setupMultiTouchSupport();

        // Apple Pencil支持
        this.setupApplePencilSupport();

        // 显示多点触控提示
        this.showMultiTouchHint();
    }

    // 高DPI画布优化
    optimizeCanvasForHighDPI() {
        const canvas = this.sandboxCanvas.canvas;
        const ctx = this.sandboxCanvas.ctx;
        const devicePixelRatio = window.devicePixelRatio || 1;

        if (devicePixelRatio > 1) {
            const rect = canvas.getBoundingClientRect();
            canvas.width = rect.width * devicePixelRatio;
            canvas.height = rect.height * devicePixelRatio;
            ctx.scale(devicePixelRatio, devicePixelRatio);
            canvas.style.width = rect.width + 'px';
            canvas.style.height = rect.height + 'px';
        }
    }

    // 多点触控支持
    setupMultiTouchSupport() {
        const canvas = this.sandboxCanvas.canvas;
        let touches = {};

        canvas.addEventListener('touchstart', (e) => {
            e.preventDefault();
            for (let i = 0; i < e.changedTouches.length; i++) {
                const touch = e.changedTouches[i];
                touches[touch.identifier] = {
                    x: touch.clientX,
                    y: touch.clientY,
                    startTime: Date.now()
                };
            }
        });

        canvas.addEventListener('touchmove', (e) => {
            e.preventDefault();
            // 处理多点触控手势
            if (e.touches.length === 2) {
                this.handlePinchGesture(e.touches);
            }
        });

        canvas.addEventListener('touchend', (e) => {
            e.preventDefault();
            for (let i = 0; i < e.changedTouches.length; i++) {
                const touch = e.changedTouches[i];
                delete touches[touch.identifier];
            }
        });
    }

    // Apple Pencil支持
    setupApplePencilSupport() {
        const canvas = this.sandboxCanvas.canvas;

        canvas.addEventListener('touchstart', (e) => {
            for (let i = 0; i < e.touches.length; i++) {
                const touch = e.touches[i];
                if (touch.touchType === 'stylus') {
                    // Apple Pencil检测到，可以启用压感等功能
                    console.log('检测到Apple Pencil');
                    this.handleApplePencilInput(touch);
                }
            }
        });
    }

    // 处理Apple Pencil输入
    handleApplePencilInput(touch) {
        // 根据压力调整画笔大小
        if (touch.force !== undefined) {
            const pressure = touch.force;
            const dynamicBrushSize = Math.max(1, this.sandboxCanvas.brushSize * pressure * 2);
            this.sandboxCanvas.setBrushSize(dynamicBrushSize);
        }
    }

    // 处理捏合手势
    handlePinchGesture(touches) {
        // 计算两点间距离，实现缩放功能
        const touch1 = touches[0];
        const touch2 = touches[1];
        const distance = Math.sqrt(
            Math.pow(touch2.clientX - touch1.clientX, 2) +
            Math.pow(touch2.clientY - touch1.clientY, 2)
        );

        // 这里可以实现画布缩放功能
        console.log('捏合手势距离:', distance);
    }

    // 全屏模式切换
    toggleFullscreen() {
        const sandboxArea = document.querySelector('.sandbox-area');

        if (!document.fullscreenElement) {
            // 进入全屏
            if (sandboxArea.requestFullscreen) {
                sandboxArea.requestFullscreen();
            } else if (sandboxArea.webkitRequestFullscreen) {
                sandboxArea.webkitRequestFullscreen();
            } else if (sandboxArea.msRequestFullscreen) {
                sandboxArea.msRequestFullscreen();
            }

            // 添加全屏样式
            sandboxArea.classList.add('fullscreen-canvas');

            // 添加退出按钮
            this.addFullscreenExitButton();

        } else {
            // 退出全屏
            if (document.exitFullscreen) {
                document.exitFullscreen();
            } else if (document.webkitExitFullscreen) {
                document.webkitExitFullscreen();
            } else if (document.msExitFullscreen) {
                document.msExitFullscreen();
            }

            sandboxArea.classList.remove('fullscreen-canvas');
            this.removeFullscreenExitButton();
        }

        // 重新调整画布大小
        setTimeout(() => {
            this.sandboxCanvas.resizeCanvas();
        }, 100);
    }

    // 添加全屏退出按钮
    addFullscreenExitButton() {
        const exitBtn = document.createElement('button');
        exitBtn.className = 'fullscreen-exit';
        exitBtn.innerHTML = '×';
        exitBtn.id = 'fullscreen-exit-btn';
        exitBtn.addEventListener('click', () => this.toggleFullscreen());
        document.body.appendChild(exitBtn);
    }

    // 移除全屏退出按钮
    removeFullscreenExitButton() {
        const exitBtn = document.getElementById('fullscreen-exit-btn');
        if (exitBtn) {
            exitBtn.remove();
        }
    }

    // 启用对象放置模式
    enableObjectPlacement(objectType) {
        this.objectPlacementMode = objectType;
        const canvas = this.sandboxCanvas.canvas;

        // 改变光标样式
        canvas.style.cursor = 'crosshair';

        // 显示提示
        this.showNotification(`点击画布放置${objectType === 'building' ? '建筑' : '树木'}`, 'info');

        // 临时绑定点击事件
        const placeObject = (e) => {
            const pos = this.sandboxCanvas.getMousePos(e);

            if (objectType === 'building') {
                this.addBuilding(pos.x, pos.y);
            } else if (objectType === 'tree') {
                this.addTree(pos.x, pos.y);
            }

            // 恢复正常模式
            canvas.style.cursor = 'crosshair';
            canvas.removeEventListener('click', placeObject);
            this.objectPlacementMode = null;
        };

        canvas.addEventListener('click', placeObject);
    }

    // 显示手势提示
    showGestureHint() {
        const hint = document.createElement('div');
        hint.className = 'gesture-hint';
        hint.textContent = '用手指在画布上绘制，双指可缩放';
        document.body.appendChild(hint);

        setTimeout(() => {
            if (hint.parentNode) {
                hint.parentNode.removeChild(hint);
            }
        }, 4000);
    }

    // 显示多点触控提示
    showMultiTouchHint() {
        const hint = document.createElement('div');
        hint.className = 'multitouch-support';
        hint.textContent = '支持Apple Pencil和多点触控';
        document.querySelector('.sandbox-area').appendChild(hint);

        setTimeout(() => {
            if (hint.parentNode) {
                hint.parentNode.removeChild(hint);
            }
        }, 4000);
    }

    // 处理屏幕方向变化
    handleOrientationChange() {
        // 重新优化布局
        setTimeout(() => {
            if (window.DeviceOrientationEvent) {
                const orientation = screen.orientation || screen.mozOrientation || screen.msOrientation;
                console.log('屏幕方向:', orientation);

                // 根据方向调整界面
                if (orientation && orientation.angle) {
                    document.body.setAttribute('data-orientation', orientation.angle);
                }
            }
        }, 500);
    }

    // 显示通知
    showNotification(message, type = 'info') {
        const notification = document.createElement('div');
        notification.style.cssText = `
            position: fixed;
            top: 20px;
            right: 20px;
            padding: 15px 20px;
            background: ${type === 'error' ? '#e74c3c' : '#3498db'};
            color: white;
            border-radius: 5px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.2);
            z-index: 1000;
            font-size: 14px;
            max-width: 300px;
            animation: slideIn 0.3s ease-out;
        `;
        notification.textContent = message;

        document.body.appendChild(notification);

        setTimeout(() => {
            if (notification.parentNode) {
                notification.style.animation = 'slideOut 0.3s ease-in';
                setTimeout(() => {
                    if (notification.parentNode) {
                        notification.parentNode.removeChild(notification);
                    }
                }, 300);
            }
        }, 4000);
    }
}

// 创建全局应用实例
window.sandboxApp = new SandboxApp();

// 导出一些便捷的全局函数
window.addBuilding = (x, y, color) => window.sandboxApp.addBuilding(x, y, color);
window.addTree = (x, y) => window.sandboxApp.addTree(x, y);
window.addRoad = (x, y, endX, endY) => window.sandboxApp.addRoad(x, y, endX, endY);
window.getAppStatus = () => window.sandboxApp.getStatus();
window.exportSandbox = () => window.sandboxApp.exportData();
window.importSandbox = (data) => window.sandboxApp.importData(data);

// 调试信息
console.log('沙盘应用已加载，可用的全局函数:');
console.log('- addBuilding(x, y, color): 添加建筑');
console.log('- addTree(x, y): 添加树木');
console.log('- addRoad(x, y, endX, endY): 添加道路');
console.log('- getAppStatus(): 获取应用状态');
console.log('- exportSandbox(): 导出沙盒数据');
console.log('- importSandbox(data): 导入沙盒数据');